#include "qalphachooser.h"

QAlphaChooser::QAlphaChooser(QWidget *parent) :
        QWidget(parent)
{
    setAttribute(Qt::WA_StaticContents);
    setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
    bg_color = QColor::fromRgb(255,255,255);
    hl_color = QColor::fromRgb(0,0,100);
    setMouseTracking(true);
    choosedX = choosedY = 0;
    setWindowFlags(Qt::Popup);
}

void QAlphaChooser::mouseMoveEvent ( QMouseEvent * event )
{
    int nx = (event->x() - 4)/ cellSize();
    int ny = (event->y() - 4)/ cellSize();
    if(nx != choosedX || ny != choosedY)
    {
        choosedX = nx; choosedY = ny;
        repaint();
    }
}

void QAlphaChooser::mousePressEvent ( QMouseEvent * event )
{
    if(event->buttons() & Qt::LeftButton)
    {
        if(rect().contains(event->pos()))
            emit clicked(QChar(0x430 + choosedY*8 + choosedX));
        else
            emit clicked(QChar(0));
    }
}

void QAlphaChooser::drawCell(int x, int y, bool hl)
{
    int s = cellSize();
    QPainter painter(this);
    QRect rect(x, y, s, s);
    if(hl)
        painter.setBrush(QBrush(hl_color));
    else
        painter.setBrush(QBrush(bg_color));
    painter.drawRect(rect);
}

QColor QAlphaChooser::getHlColor() const
{
    return hl_color;
}

void QAlphaChooser::setHlColor(const QColor &color)
{
    if(hl_color != color)
    {
        hl_color = color;
        update();
    }
}

QColor QAlphaChooser::getBgColor() const
{
    return hl_color;
}

void QAlphaChooser::setBgColor(const QColor &color)
{
    if(bg_color != color)
    {
        bg_color = color;
        update();
    }
}

void QAlphaChooser::paintEvent(QPaintEvent *)
{
    int s = cellSize();
    QPainter painter(this);
    painter.setBrush(QBrush(bg_color));
    painter.setPen(Qt::SolidLine);
    painter.drawRect(QRect(0, 0, s*8 + 4, s*4 + 4));
    for ( int i = 0; i < 32; i++)
    {
        int xpos, ypos;
        ypos = i>>3;
        xpos = i&7;
        QFontMetrics metrics(font());
        QString str(QChar(0x430 + i));
        if(xpos == choosedX && ypos == choosedY)
        {
            painter.drawRect(xpos*s +2, ypos*s+2, s, s);
        }
        QSize csize = metrics.size(Qt::TextSingleLine, str);
        painter.drawText(xpos*s + ((s - csize.width())>>1) + 2,
                         ypos*s + ((s - csize.height())>>1) + metrics.ascent() + 2,
                         str);
    }
}

int QAlphaChooser::cellSize() const
{
    QFontMetrics metrics(font());
    return (metrics.height() + 2);
}

QSize QAlphaChooser::sizeHint() const
{
    int cs = cellSize();
    return QSize(4 + 8*cs + 1, 4 + 4*cs + 1);
}
